package com.st.lotte.view;

import ch.qos.logback.classic.Logger;

import com.st.lotte.model.TLO_DELY_TRCE_RECV_IF;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import sun.util.logging.resources.logging;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Handlake on 2014. 4. 24..
 */
public class DownloadView extends AbstractPOIExcelView {

    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public Workbook createWorkbook() {
        return new XSSFWorkbook();
    }

    private String getBrowser(HttpServletRequest request) {
        String header =request.getHeader("User-Agent");
        if (header.contains("MSIE")) {
            return "MSIE";
        } else if(header.contains("Chrome")) {
            return "Chrome";
        } else if(header.contains("Opera")) {
            return "Opera";
        }
        return "Firefox";
    }

    @Override
    public void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = (String)model.get("fileName");

        String header = getBrowser(request);
        System.out.println(request.getHeader("User-Agent"));
        if (header.contains("MSIE")) {
            String docName = URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename=" + docName + ";");
        } else if (header.contains("Firefox")) {
            String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");
        } else if (header.contains("Opera")) {
            String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");
        } else if (header.contains("Chrome")) {
            String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");
        }
        String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\";");
        response.setHeader("Content-Transfer-Encoding", "binary");

        Sheet sheet = workbook.createSheet("Sample sheet");

        Map<String, Object[]> data = new LinkedHashMap<String, Object[]>();
        List<TLO_DELY_TRCE_RECV_IF> products = (List<TLO_DELY_TRCE_RECV_IF>)model.get("products");

        /*
         * <td>수신일자(롯데기준)</td>
			<td>운송장번호</td>
			<td>주문번호</td>
			<td>택배사</td>
			<td>배송상태</td>
			<td>현재상태</td>
			<td>출발/도착</td>
			<td>택배사 처리일시</td>
         * */
        data.put("0", new Object[]{"수신일자(롯데기준)", "운송장번호", "주문번호",
                "택배사", "배송상태", "현재상태", "출발/도착", "택배사 처리일시"});

        System.out.println("products = "+products);
        for(int i = 0 ; i < products.size() ; i++) {
        	TLO_DELY_TRCE_RECV_IF product = products.get(i);
            data.put("" + (i +1), new Object[] {product.getRECV_DATE(), product.getSLIP_NO(), product.getCMBN_ORD_NO(),
                    product.getHODECO_CODE(), product.getTRCE_STAT_CODE(), product.getRMK4(), product.getTRCE_STAT_DIV_CODE(), product.getTRCE_STAT_PROC_DT()});
        }


        Set<String> keyset = data.keySet();
        int rownum = 0;
        for (String key : keyset) {
            Row row = sheet.createRow(rownum++);
            Object [] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellnum++);
                if(obj instanceof Date) {
                    cell.setCellValue(df.format((Date)obj));
                } else if(obj instanceof Boolean)
                    cell.setCellValue((Boolean)obj);
                else if(obj instanceof String)
                    cell.setCellValue((String)obj);
                else if(obj instanceof Double)
                    cell.setCellValue((Double)obj);
            }
        }
    }
}